package com.example.mycarcalling.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.mycarcalling.bean.Application;
import com.example.mycarcalling.bean.User;
import com.example.mycarcalling.service.UserService;
import com.example.mycarcalling.utils.BaseException;
import com.example.mycarcalling.utils.BaseResponse;
import com.example.mycarcalling.utils.ResponseCode;
import com.example.mycarcalling.utils.ResponseResult;
import com.example.mycarcalling.vo.Passwords;
import com.example.mycarcalling.vo.PhoneAndNickName;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
//@BaseResponse
@RequestMapping(value = "user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     *用户登录
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/login")
    public ResponseResult login(@RequestBody String str){
        JSONObject jsonArray = null;

        try {
            jsonArray = JSONObject.parseObject(str);
//            System.out.println(str);
            String account = jsonArray.getString("account");
            String password = jsonArray.getString("password");
            User user = userService.login(account,password);
            if(user.equals(null)){
                throw new BaseException(ResponseCode.RESOURCES_NOT_EXIST);
            }else {
                StpUtil.login(user.getId());
                System.out.println(StpUtil.isLogin());
                int updateResult = userService.updateLoginTime();
                if(updateResult==1){
                    return new ResponseResult(200,"success",StpUtil.getTokenValueByLoginId(user.getId()));
                }else {
                    return new ResponseResult(500,"failed","更新登录时间失败");
                }
            }
        }catch (Exception e){
            return new ResponseResult(500,"failed","服务器异常");
        }
//        return new ResponseResult(10000,"success",StpUtil.getLoginIdByToken(""));
    }

    /**
     *用户注册
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/register")
    public ResponseResult register(@RequestBody User user){
        Long userId = null;
        try {
            userId = userService.register(user);
            if(null==userId){
                return new ResponseResult(500,"failed",userId);
            }
            return new ResponseResult(200,"success",userId);
        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, "failed", null);
        }
    }

    /**
     * 根据token获取登录用户信息
     * @param request {"cctoken":"asdasd-asdasdas-asdasd-asdasda"}
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/getUserInfo")
    public ResponseResult getUserInfoByToken(HttpServletRequest request) {
        User user = null;
        try {
            user = userService.findUserById(StpUtil.getLoginIdAsLong());
//            if (user == null) {
//                throw new Exception("token无效");
//            }
            System.out.println(user.getLoginTime());
            return new ResponseResult(200, "success", user);
        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, "failed", null);
        }
    }

    /**
     * 乘客用户获取接单司机账号信息
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "/getDriverUserName")
    public ResponseResult getDriverUserName(){
        String driverUserName = null;
        try {
            if(userService.IsDriver(StpUtil.getLoginIdAsLong())){
                throw new Exception("没有乘客权限");
            }
            driverUserName = userService.getDriver(StpUtil.getLoginIdAsLong());
            if(null != driverUserName){
                return new ResponseResult(200,"success",driverUserName);
            }
            return  new ResponseResult(201,"没有找到司机",null);
        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, "failed", null);
        }
    }

    /**
     * 接单司机用户获取乘客账号信息
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "/getPassengerUser")
    public ResponseResult getPassengerUser(){
        User user = null;
        try {
            if(userService.IsDriver(StpUtil.getLoginIdAsLong())){
                user = userService.getPassenger(StpUtil.getLoginIdAsLong());
                if(null != user){
                    return new ResponseResult(200,"success",user);
                }
                return  new ResponseResult(201,"没有找到乘客信息",null);
            }
            throw new Exception("没有乘客权限");

        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, "failed", null);
        }
    }

    /**
     * 用户更新昵称或手机号
     * @param userInfo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/updateUserInfo")
    public ResponseResult updateUserInfo(@RequestBody PhoneAndNickName userInfo) {
        int result;
        try {
            User user = new User();

            user.setId(StpUtil.getLoginIdAsLong());
            if (null != userInfo.getNickName()){
                System.out.println(userInfo.getNickName());
                user.setNickname(userInfo.getNickName());
            }
            if(null != userInfo.getPhone()){
                System.out.println(userInfo.getPhone());
                user.setPhoneNumber(userInfo.getPhone());
            }
            result = userService.updateUserInfo(user);
            System.out.println("result:"+result);
            if(result==1){
                return  new ResponseResult(200,"success","0");
            }

            return  new ResponseResult(501,"修改失败","1");

        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, e.getMessage(), null);
        }
    }

    /**
     * 修改密码
     * @param passwords
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/changePassword")
    public ResponseResult changePassword(@RequestBody Passwords passwords){
        int result;
        try {
            User oldUser = null;
            User updateUser = new User();
            oldUser = userService.findUserById(StpUtil.getLoginIdAsLong());
            if(null !=oldUser){
                if(oldUser.getPassword().equals(passwords.getOldPassword())){
                    updateUser.setId(StpUtil.getLoginIdAsLong());
                    updateUser.setPassword(passwords.getConfirmPassword());
                    result = userService.changePassword(updateUser);
                    System.out.println(result);
                    if(result==1){
                        StpUtil.logout(StpUtil.getLoginIdAsLong());
                        return  new ResponseResult(200,"success","");
                    }
                }
                return  new ResponseResult(501,"原密码错误","");

            }
            throw new Exception("查询用户异常");


        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        }catch (Exception e){
            return new ResponseResult(500, e.getMessage(), null);
        }
    }

    /**
     * 通过某个用户id获取用户信息
     * @param userId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "getUser/{userId}")
    public ResponseResult getUser(@PathVariable("userId") Long userId){
        User user = null;
        try {

            StpUtil.getLoginIdAsLong();
            System.out.println(userId);
            user = userService.findUserById(userId);
            if(null==user){
                throw new Exception("获取用户信息失败");
            }
            return new ResponseResult(200,"success",user);

        }catch (NotLoginException e){
            return new ResponseResult(503,"failed",e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(500,"failed",e.getMessage());
        }
    }
}
